// pages/choujiang/choujiang.js
var utils = require('../../utils/api.js');
var base64 = require('../../utils/base64.js');
var md5 = require('../../utils/md5.js');

let canRoll = true, //加控制，防止用户点击两次
  num = 1, //用在动画上，让用户在第二次点击的时候可以接着上次转动的角度继续转
  lotteryArrLen = 0, //放奖品的数组的长度
  lottery = ['奖品1', '奖品2', '奖品2', '奖品2', '奖品2', '奖品2']; //放奖品
Page({
  data: {
    iszhongjiang: false,
    isweizhongjiang: false,
    allLoading: false, //加载判断
    goodsid: null,     //商品ID
    goodsTypeId: null, //商品类别
    tempDataList: [],
    lottery: [],
  },

  onLoad(options) {
    let that = this;
    that.setData({ //参数初始化赋值
      goodsid: options.id,
      goodsTypeId: options.goodsTypeId,
    })
    that.CommonShowLoadingMsg('加载中')
    // that.setData({ lottery: that.data.tempDataList })
    let aniData = wx.createAnimation({ //创建动画对象
      duration: 5000,
      timingFunction: 'ease',
      // delay:100,
    });
    this.aniData = aniData; //将动画对象赋值给this的aniData属性
  },
  setPlateData() { //设置奖品数组
    lotteryArrLen = lottery.length; //获取奖品数组的长度，用来判断
    if (lotteryArrLen < 2) { //数组的奖品只有一个，扩展数组的长度到4
      let evenArr = new Array(4); //创建一个数组，方便操作。
      for (let i = 0; i < 4; i++) {
        if (i % 2 == 1) { //这里为什么要取1是为了在默认的界面将指针放在谢谢的地方，防止别人拿着中奖的截图来要奖品
          evenArr[i] = lottery[0]; //将原数组的内容赋值到新的数组
        } else {
          evenArr[i] = '谢谢' //在数组中间隔插入谢谢
        }
      }
      lottery = [...evenArr]; //将整合好的数组赋值给lottery数组
    } else { //数组中的奖品超过1个，则正常扩展数组，扩展的数组为原来的2倍
      let dataLen = 0; //用来放原来数组的索引
      let evenArr = new Array(lotteryArrLen * 2); //创建扩展数组
      for (let i = 0; i < (lotteryArrLen * 2); i++) {
        if (i % 2 == 1) {
          evenArr[i] = lottery[dataLen]; //将原来数组的值赋值给新数组
          dataLen++; //原来数组的索引加一
        } else {
          evenArr[i] = '谢谢'
        }
      }
      lottery = [...evenArr]; //将整合好的数组赋值给lottery数组
    }

    lotteryArrLen = lottery.length; //获取新的数组长度
    this.setData({
      lottery: lottery //设置好值，用于页面展示
    })
  },
  /**
 * 生命周期函数--监听页面显示
 */
  onShow: function () {
    var that = this
    that.setData({
      iszhongjiang: false
    })
    that.getTurntableInfoReq() //执行获取转盘信息    
  },
  startRollTap() { //开始转盘
    let that = this;
    //提交给服务器请求
    that.setTurntableInfoReq()
    if (canRoll) {
      canRoll = false;
      let aniData = this.aniData; //获取this对象上的动画对象
      let rightNum = ~~(Math.random() * lotteryArrLen); //生成随机数
      console.log(`随机数是${rightNum}`);
      console.log(`奖品是：${lottery[rightNum]}`);
      aniData.rotate(3600 * num - 360 / lotteryArrLen * rightNum).step(); //设置转动的圈数
      this.setData({
        aniData: aniData.export()
      });
      num++;
      canRoll = true;
      setTimeout(function () {
        that.setData({
          // iszhongjiang: true
        });
      }, 2000)
    }
  },
  tipbgtap: function () {
    this.setData({
      iszhongjiang: false,
      isweizhongjiang: false
    })
  },
  zaiwanyici: function () {
    this.setData({
      isweizhongjiang: false
    })
  },
  /**
   * 转盘公用信息
   */
  CommonShowLoadingMsg: function (msg) {
    wx.showLoading({
      title: msg,
      mask: true,
    })
  },
  /**
   * 公用信息
   */
  CommonShowMsg: function (msg) {
    wx.showToast({
      title: msg,
      mask: true,
      icon: 'none',
      duration: 3000,
    })
  },
  /**
   * 获取转盘信息
   */
  getTurntableInfoReq: function () {
    var that = this
    wx.request({
      url: getApp().globalData.requestUrl + '/getReceiptInformation',
      method: "post",
      data: {
        paramList: base64.CusBASE64.encoder('{"serverSessionKey":"' + wx.getStorageSync('serverSessionKey') + '","id":"' + that.data.goodsid + '","goodsTypeId":"' + that.data.goodsTypeId + '"}')
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        // console.log(res)
        if (res.statusCode == 200) { //判断wx.request请求是否成功
          if (res.data) {
            var dat = utils.stringToJson(utils.ascii2native(res.data))
            console.log('interface:getReceiptInformation')
            console.log(dat)
            if (dat.status == 0) {
              if (dat.dataList) {
                // 数据赋值
                var tempDataList = []
                for (var i = 0; i < dat.dataList.prizeList.length; i++) {
                  tempDataList[i] = dat.dataList.prizeList[i].prizeName
                }
                that.setData({
                  tempDataList: tempDataList,
                  lottery: tempDataList
                })
                console.log(that.data.lottery)
                that.setPlateData(); //执行设置转盘表面的文字  
                // 隐藏信息
                wx.hideLoading()
                that.setData({ allLoading: true })
              } else { //获取信息错误
                that.CommonShowMsg('数据错误')
              }
            } else {
              that.CommonShowMsg(dat.errorMsg)
            }
          } else {//服务器没有返回数据
            that.CommonShowMsg('数据错误')
          }
        } else {//请求失败
          that.CommonShowMsg('数据错误')
        }
      },
      fail: function (res) {
      },
      complete: function () {
      },
    })
  },
  /** 
   * 提交转盘请求
   */
  setTurntableInfoReq: function () {
    var that = this
    // getPrizesState
    wx.request({
      url: getApp().globalData.requestUrl + '/getPrizesState',
      method: "post",
      data: {
        paramList: base64.CusBASE64.encoder('{"serverSessionKey":"' + wx.getStorageSync('serverSessionKey') + '","id":"' + that.data.goodsid + '"}')
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        // console.log(res)
        if (res.statusCode == 200) { //判断wx.request请求是否成功
          if (res.data) {
            var dat = utils.stringToJson(utils.ascii2native(res.data))
            console.log('interface:getPrizesState')
            console.log(dat)
            if (dat.status == 0) {
              if (dat.dataList) {

              } else { //获取信息错误
                that.CommonShowMsg('数据错误')
              }
            } else {
              that.CommonShowMsg(dat.errorMsg)
            }
          } else {//服务器没有返回数据
            that.CommonShowMsg('数据错误')
          }
        } else {//请求失败
          that.CommonShowMsg('数据错误')
        }
      },
      fail: function (res) {
      },
      complete: function () {
      },
    })

  },
  /**
   * 轮询获取转盘中奖信息
   */

})